﻿
namespace Patterns4Net.ArchitectureExplorer.Diagram.Services.Relations
{
    using Mono.Cecil;
    using ArchitectureExplorer.Diagram.Relations;
    using Core.CecilExtensions;
    using Attributes.Relations;

    /// <summary>
    /// Adds relations of type <see cref="Composition"/> into the diagram.
    /// </summary>
    [DiagramUpdaterExport(Order = 20)]
    public class CompositionProvider : RelationsProvider
    {
        protected override void Visit(TypeInfo typeInfo, TypeDefinition typeDefinition)
        {
            foreach (var fieldDefinition in typeDefinition.Fields)
            {
                if (fieldDefinition.HasAttribute<CompositionAttribute>())
                {
                    this.AddRelationIfExists(typeInfo, this.GetTypeAndCardinality(fieldDefinition));
                }
            }
        }

        protected override Relation CreateRelation(DiagramElement source, DiagramElement target, Cardinality cardinality)
        {
            return new Composition(source, target, cardinality);
        }

        protected override bool IsMadeObsoleteBy(Relation relation)
        {
            return relation.GetType() == typeof(Aggregation) ||
                   relation.GetType() == typeof(Composition) ||
                   relation.GetType() == typeof(Association);
        }
    }
}
